
const con = require('../utils/myconn.js')

exports.getAllpost = function (data, callback) {

    // 查询数据
    let sql = `SELECT posts.*,categories.name,users.nickname 
    FROM posts 
    JOIN users ON posts.user_id=users.id
    JOIN categories ON posts.category_id=categories.id
    where 1=1 `
    // if (data.cate && data.cate != 'all') { // 有没有传递分类数据
    //     sql += ` and category_id = ${data.cate}`
    // }
    // if (data.status && data.status != 'all') {
    //     sql += ` and posts.status ='${data.status}'`
    // }

    // sql += ` order by id desc
    //         limit ${(data.pageNum - 1) * data.pageSize},${data.pageSize}`
    // 判断不是全选分类就加条件赛选
    if (data.cate && data.cate != 'all') {
        sql += ` and category_id = ${data.cate}`
    }
    if (data.status && data.status != 'all') {
        sql += ` and posts.status ='${data.status}'`
    }

    sql += `order by id desc
    limit ${(data.pageNum - 1) * data.pageSize},${data.pageSize}`


    con.query(sql, (err, resluts) => {
        if (err) {
            callback(err)
        } else {
            // 再查询总页数返回给客户端
            sql =
                `select count(*) as cnt
                    from posts
                    join users on posts.user_id = users.id
                    join categories on posts.category_id = categories.id
                    where 2=2`
            if (data.cate && data.cate != 'all') { // 有没有传递分类数据
                sql += ` and category_id = ${data.cate}`
            }
            if (data.status && data.status != 'all') {
                sql += ` and posts.status ='${data.status}'`
            }


            con.query(sql, (err2, res2) => {
                if (err2) {
                    callback(err2)
                } else {

                    // callback(null, { data: resluts, total: res2[0].cnt })
                    callback(null, { data: resluts, total: res2[0].cnt })

                }
            })

        }

    })

}